<?php 
	require_once('./inc/config.php');
	class DBConnector {
		private static $connection;
		
		public function connect() {		
			if (!self::$connection) {
				global $config;
				self::$connection = @mysql_connect($config['dbhost'], $config['dbuser'], $config['dbpass']);
				if (!self::$connection) {
					die('MySQL Error: Coldn\'t connect to the DB Server.');
				}
				$sel = @mysql_select_db($config['dbname'], self::$connection);
				if (!$sel) {
					die('MySQL Error: '.mysql_error(self::$connection));
				}
				mysql_query("SET NAMES utf8", self::$connection);
			}
		}
		
		public function query($query) {
			$result = @mysql_query($query, self::$connection);
			if (!$result) {
				$this->error($query);
			} else {
				return $result;
			}
		}
		
		public function result($query, $iterator = null) {
			$res = $this->query($query);
			//$out = array();
			if (is_null($iterator) || empty($iterator) || !is_subclass_of($iterator, 'DBIterator')) {
				$iterator = new DefaultDBIterator();
			}			
			while ($row = mysql_fetch_array($res)) {
				$iterator->iterate($row);
			}
			return $iterator;
		}
		
		public function result_array($query) {
			$clData = $this->result($query);
			return $clData->getData();
		}
		
		public function count($table, $condition) {
			$count = $this->result('SELECT COUNT(*) AS cnt FROM '.$table.' WHERE '.$condition);	
			$cnt = $count->getData();
			return $cnt[0]['cnt'];
		}
		
		public function escape($str) {
			return mysql_real_escape_string($str, self::$connection);
		}
		
		public function error($query) {		
			$error = mysql_error(self::$connection);
			echo <<<ERR
			<div style="border: 1px solid #3d5ea3; background: #dcfaff; padding: 5px;">
				Error:<br>
				<span style="color:#da2f31; font-weight:bold">.$error.</span>
				<br>
				Query:<br>
				<span style="color:#629525; font-weight:normal">.$query.</span>
			</div>
ERR;
			throw new Exception("Query error.");
			//Кровь кишки говно, такая уж эта функиция			
		}
		
		public function close() {
			if (self::$connection) {
				mysql_close(self::$connection);
			}
		}
	}
	
	abstract class DBIterator {
		protected $dbData = array();		
		public function getData() {
			return $this->dbData;
		}		
		public abstract function iterate($row);
	}
	
	class DefaultDBIterator extends DBIterator {		
		public function iterate($row) {
			$this->dbData[] = $row;
		}
	}
?>